package com.gudaomai.ekproject.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.access.annotation.Secured;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.gudaomai.ekproject.common.CommonConstant;
import com.gudaomai.ekproject.common.CommonException;
import com.gudaomai.ekproject.common.Constant;
import com.gudaomai.ekproject.common.MsgConstant;
import com.gudaomai.ekproject.entity.Project;
import com.gudaomai.ekproject.entity.ProjectInput;
import com.gudaomai.ekproject.entity.ProjectSysuser;
import com.gudaomai.ekproject.entity.RetEntity;
import com.gudaomai.ekproject.service.IProjectService;
import com.gudaomai.ekproject.service.IProjectSysuserService;
import com.gudaomai.ekproject.web.BaseController;

import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 项目 前端控制器
 * </p>
 *
 * @author zenghualu
 * @since 2017-06-26
 */
@RestController
@RequestMapping("/ekproject/project")
public class ProjectController extends BaseController {

	@Autowired
	IProjectService projectServ;
	@Autowired
	protected MessageSource messageSource;
	@Autowired
	IProjectSysuserService projectSysuserServ;

	/**
	 * TODO:complete 添加工程 1.工程名是否存在，已经存在就报错 2.添加工程 3.把创建者添加到工程所属团队
	 * 
	 * @param pro
	 * @return
	 * @author xiaosong
	 */
	@RequestMapping(value = "/", method = RequestMethod.POST)
	public Project addProject(@RequestBody @Validated ProjectInput projectInput) throws CommonException {

		// 检测工程名是否存在[此操作前存在注解校验是否为空等,所以代码不必校验pro.getName是否为空]
		Project proj = null;
		if (projectServ.isExist(projectInput.getName())) {
			// 数据库存在该记录，拒绝执行插入操作
			// 设置返回代码为201，状态信息 @see
			// com.gudaomai.ekproject.common.CommonConstant,MsgConstant
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_FOUND,
					getMessage(MsgConstant.RET_PROJECT_ADD_ALREADY_EXIST));
		} else {

			proj = new Project();
			BeanUtils.copyProperties(projectInput, proj);
			// 数据库不存在该条记录，执行插入操作
			// 设置该记录的id_
			proj.setId(IdWorker.get32UUID());
			projectServ.insert(proj);
			// 设置返回代码200,状态信息 @see
			// com.gudaomai.ekproject.common.CommonConstant,MsgConstant
			proj.setRetCode(CommonConstant.RESULT_CODE_OK);
			proj.setRetMessage(MsgConstant.RET_PROJECT_ADD_SUCCESS);

			// TODO -等待从session里获取值
			// 更新project-sysuser表

		}

		return proj;
	}

	/**
	 * 根据id进行更新 注意部分字段不能为空，需要做输入检查
	 * 
	 * @author xiaosong
	 * @param pro
	 * @return
	 */
	@ApiOperation(value = "更新工程", notes = "")
	@RequestMapping(value = "/", method = RequestMethod.PUT)
	@Transactional(propagation = Propagation.REQUIRED)
	public RetEntity updateProject(@RequestBody @Validated ProjectInput projectInput) {

		RetEntity retEntity = new RetEntity();
		Project project = new Project();
		BeanUtils.copyProperties(projectInput, project);
		boolean updated = projectServ.updateById(project);

		if (updated) {
			// 更新成功，设置状态码为200,状态信息 @see
			// com.gudaomai.ekproject.common.CommonConstant,MsgConstant
			retEntity.setRetCode(CommonConstant.RESULT_CODE_OK);
			retEntity.setRetMessage(MsgConstant.RET_PROJECT_UPDATE_SUCCESS);
		} else {
			// 更新失败，设置状态码为304 未修改 状态信息@see
			// com.gudaomai.ekproject.common.CommonConstant,MsgConstant
			retEntity.setRetCode(CommonConstant.RESULT_CODE_NOT_MODIFIED);
			retEntity.setRetMessage(MsgConstant.RET_PROJECT_UPDATE_FAILURE);
		}

		return retEntity;
	}

	/**
	 * 根据id进行删除
	 * 
	 * @param pro
	 * @return
	 * @throws CommonException
	 */
	@ApiOperation(value = "根据id进行删除", notes = "")
	@RequestMapping(value = "/id/{id}", method = RequestMethod.DELETE)
	@Transactional(propagation = Propagation.REQUIRED)
	public RetEntity delProject(@PathVariable("id") String id) throws CommonException {

		RetEntity retEntity = new RetEntity();
		boolean deleted = projectServ.deleteById(id);
		if (deleted) {
			// 更新成功，设置状态码为200,状态信息 @see
			// com.gudaomai.ekproject.common.CommonConstant,MsgConstant
			retEntity.setRetCode(CommonConstant.RESULT_CODE_OK);
			retEntity.setRetMessage(MsgConstant.RET_PROJECT_DELETE_SUCCESS);
		} else {
			// 更新失败，设置状态码为304 未修改 状态信息@see
			// com.gudaomai.ekproject.common.CommonConstant,MsgConstant
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_MODIFIED,
					getMessage(MsgConstant.RET_PROJECT_DELETE_FAILURE));

		}

		return retEntity;
	}

	/**
	 * 根据用户id获取所属的项目列表
	 * 
	 * @param uid
	 * @return
	 * @author xiaosong
	 * @throws CommonException
	 */
	@Secured(Constant.PERMISSION_PROJECT_GET)
	@RequestMapping(value = "/uid/{uid}", method = RequestMethod.GET)
	// @ApiImplicitParams({ @ApiImplicitParam(name = "uid", value = "用户ID",
	// required = true, dataType = "String")})
	@ApiOperation(value = "根据用户id获取用户参与的项目", notes = "")
	public List<Project> getProjectByuserId(@PathVariable("uid") String uid) throws CommonException {

		// TODO:review-complete 下面的业务处理应该写到service层，在service增加一个方法，这里调用。

		// 首先在project_sysuser表获取该用户所有所属的项目id_
		List<ProjectSysuser> projectSysusers = projectSysuserServ.getProjectByuserId(uid);

		List<String> pids = new ArrayList<>();
		if (projectSysusers.size() <= 0) {
			// project_sysuser表中没有记录，拒绝执行下面代码
			return null;
		} else {
			// project_sysuser表存在记录，获取每个记录中的project_id字段，添加到list--pids中
			for (ProjectSysuser projectSysuser : projectSysusers) {
				pids.add(projectSysuser.getProjectId());
			}
		}

		// 因为project表和project_sysuser表示一对多的关系，所以从project_sysuser获得的project_id一定存在在project表中
		// 所以不必为projects作非空检查，new的目的是即使projectServ.selectBatchIds(pids）没有记录，那也只会返回null
		List<Project> projects = new ArrayList<>();
		projects = projectServ.selectBatchIds(pids);

		return projects;

	}
}
